package com.luo.backend.service;

import com.luo.backend.dto.MerchantOrderStatsResponse;
import com.luo.backend.dto.OrderResponse;
import com.luo.backend.entity.Order;
import com.luo.backend.entity.OrderItem;
import com.luo.backend.repository.OrderItemRepository;
import com.luo.backend.repository.OrderRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商家订单管理服务
 */
@Service
public class MerchantOrderService {
    
    private static final Logger logger = LoggerFactory.getLogger(MerchantOrderService.class);
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private OrderItemRepository orderItemRepository;
    
    /**
     * 获取商家订单统计
     */
    public MerchantOrderStatsResponse getOrderStats(Long merchantId) {
        logger.info("获取商家订单统计 - merchantId: {}", merchantId);
        
        // 待接单数量（状态为paid，已支付等待商家接单）
        Long pendingCount = orderRepository.countByMerchantIdAndStatus(merchantId, "paid");
        
        // 已接单（备货中）数量（状态为preparing且未发货）
        Long acceptedCount = orderRepository.countByMerchantIdAndStatusAndShippedAtIsNull(merchantId, "preparing");
        
        // 配送中数量（状态为shipping）
        Long shippingCount = orderRepository.countByMerchantIdAndStatus(merchantId, "shipping");
        
        // 今日订单
        LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime todayEnd = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        List<Order> todayOrders = orderRepository.findByMerchantIdAndCreatedAtBetween(
            merchantId, todayStart, todayEnd);
        
        Long todayCount = (long) todayOrders.size();
        
        // 今日营业额（已支付的订单）
        Long todayAmount = todayOrders.stream()
            .filter(order -> !"pending".equals(order.getStatus()) && !"cancelled".equals(order.getStatus()))
            .map(order -> order.getTotalAmount().multiply(new BigDecimal("100")).longValue())
            .reduce(0L, Long::sum);
        
        logger.info("订单统计 - 待接单: {}, 备货中: {}, 配送中: {}, 今日订单: {}, 今日营业额: {}分", 
            pendingCount, acceptedCount, shippingCount, todayCount, todayAmount);
        
        return new MerchantOrderStatsResponse(pendingCount, acceptedCount, shippingCount, todayCount, todayAmount);
    }
    
    /**
     * 获取商家订单列表
     */
    public List<OrderResponse> getOrders(Long merchantId, String status, Integer page, Integer pageSize) {
        logger.info("获取商家订单列表 - merchantId: {}, status: {}, page: {}, pageSize: {}", 
            merchantId, status, page, pageSize);
        
        List<Order> orders;
        
        if (status != null && !status.isEmpty() && !"all".equals(status)) {
            orders = orderRepository.findByMerchantIdAndStatusOrderByCreatedAtDesc(merchantId, status);
        } else {
            // ⚠️ 商家端只显示已支付及之后状态的订单，不显示 pending（待支付）状态
            orders = orderRepository.findByMerchantIdOrderByCreatedAtDesc(merchantId);
            // 过滤掉 pending 状态的订单
            orders = orders.stream()
                .filter(order -> !"pending".equals(order.getStatus()))
                .collect(Collectors.toList());
        }
        
        logger.info("查询到订单数量: {}", orders.size());
        if (!orders.isEmpty()) {
            logger.info("第一条订单 - ID: {}, OrderNo: {}, MerchantId: {}, MerchantName: {}", 
                orders.get(0).getId(), orders.get(0).getOrderNo(), 
                orders.get(0).getMerchantId(), orders.get(0).getMerchantName());
        }
        
        // 简单分页（实际项目建议使用 Spring Data 的 Pageable）
        int start = (page - 1) * pageSize;
        int end = Math.min(start + pageSize, orders.size());
        
        if (start >= orders.size()) {
            return new ArrayList<>();
        }
        
        List<Order> pagedOrders = orders.subList(start, end);
        
        // 安全验证：确保所有订单都属于该商家
        for (Order order : pagedOrders) {
            if (!order.getMerchantId().equals(merchantId)) {
                logger.error("!!!安全警告!!! 发现不属于商家的订单 - 期望merchantId: {}, 实际merchantId: {}, 订单ID: {}", 
                    merchantId, order.getMerchantId(), order.getId());
                throw new RuntimeException("数据安全错误：查询到不属于该商家的订单");
            }
        }
        
        return pagedOrders.stream()
            .map(order -> {
                OrderResponse response = new OrderResponse(order);
                // 加载订单商品
                List<OrderItem> items = orderItemRepository.findByOrderId(order.getId());
                response.setItems(items.stream()
                    .map(OrderResponse.OrderItemResponse::new)
                    .collect(Collectors.toList()));
                return response;
            })
            .collect(Collectors.toList());
    }
    
    /**
     * 获取订单详情
     */
    public OrderResponse getOrderDetail(Long merchantId, Long orderId) {
        logger.info("获取订单详情 - merchantId: {}, orderId: {}", merchantId, orderId);
        
        Order order = orderRepository.findById(orderId)
            .orElseThrow(() -> new RuntimeException("订单不存在"));
        
        // 验证订单属于该商家
        if (!order.getMerchantId().equals(merchantId)) {
            throw new RuntimeException("无权访问该订单");
        }
        
        OrderResponse response = new OrderResponse(order);
        
        // 加载订单商品
        List<OrderItem> items = orderItemRepository.findByOrderId(orderId);
        response.setItems(items.stream()
            .map(OrderResponse.OrderItemResponse::new)
            .collect(Collectors.toList()));
        
        return response;
    }
    
    /**
     * 接单
     */
    @Transactional
    public void acceptOrder(Long merchantId, Long orderId) {
        logger.info("商家接单 - merchantId: {}, orderId: {}", merchantId, orderId);
        
        Order order = orderRepository.findById(orderId)
            .orElseThrow(() -> new RuntimeException("订单不存在"));
        
        // 验证订单属于该商家
        if (!order.getMerchantId().equals(merchantId)) {
            throw new RuntimeException("无权操作该订单");
        }
        
        // 只有已支付状态才能接单（用户已支付，等待商家接单）
        if (!"paid".equals(order.getStatus())) {
            throw new RuntimeException("订单状态不允许接单，当前状态: " + order.getStatus());
        }
        
        order.setStatus("preparing");
        order.setAcceptedAt(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());
        
        orderRepository.save(order);
        
        logger.info("接单成功 - orderId: {}", orderId);
    }
    
    /**
     * 拒单
     */
    @Transactional
    public void rejectOrder(Long merchantId, Long orderId, String reason) {
        logger.info("商家拒单 - merchantId: {}, orderId: {}, reason: {}", merchantId, orderId, reason);
        
        Order order = orderRepository.findById(orderId)
            .orElseThrow(() -> new RuntimeException("订单不存在"));
        
        // 验证订单属于该商家
        if (!order.getMerchantId().equals(merchantId)) {
            throw new RuntimeException("无权操作该订单");
        }
        
        // 只有已支付状态才能拒单（商家拒绝已支付的订单，需要退款）
        if (!"paid".equals(order.getStatus())) {
            throw new RuntimeException("订单状态不允许拒单，当前状态: " + order.getStatus());
        }
        
        order.setStatus("cancelled");
        order.setCancelReason(reason != null ? reason : "商家拒绝接单");
        order.setCancelledAt(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());
        
        orderRepository.save(order);
        
        logger.info("拒单成功 - orderId: {}", orderId);
    }
    
    /**
     * 开始备货
     */
    @Transactional
    public void startPreparing(Long merchantId, Long orderId) {
        logger.info("开始备货 - merchantId: {}, orderId: {}", merchantId, orderId);
        
        Order order = orderRepository.findById(orderId)
            .orElseThrow(() -> new RuntimeException("订单不存在"));
        
        // 验证订单属于该商家
        if (!order.getMerchantId().equals(merchantId)) {
            throw new RuntimeException("无权操作该订单");
        }
        
        // 已经接单的状态才能开始备货
        if (!"preparing".equals(order.getStatus())) {
            throw new RuntimeException("订单状态不允许该操作");
        }
        
        // 这里可以添加额外的备货逻辑，目前只是确认状态
        order.setUpdatedAt(LocalDateTime.now());
        orderRepository.save(order);
        
        logger.info("开始备货 - orderId: {}", orderId);
    }
    
    /**
     * 开始配送
     */
    @Transactional
    public void startShipping(Long merchantId, Long orderId) {
        logger.info("开始配送 - merchantId: {}, orderId: {}", merchantId, orderId);
        
        Order order = orderRepository.findById(orderId)
            .orElseThrow(() -> new RuntimeException("订单不存在"));
        
        // 验证订单属于该商家
        if (!order.getMerchantId().equals(merchantId)) {
            throw new RuntimeException("无权操作该订单");
        }
        
        // 只有备货中状态才能开始配送
        if (!"preparing".equals(order.getStatus())) {
            throw new RuntimeException("订单状态不允许该操作");
        }
        
        order.setStatus("shipping");
        order.setShippedAt(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());
        
        orderRepository.save(order);
        
        logger.info("开始配送成功 - orderId: {}", orderId);
    }
}

